package com.zetxek.meteogalicia.parsers;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.zetxek.meteogalicia.datasets.Localidad;

public class LocalidadesParser extends DefaultHandler {

	// ===========================================================
	// Fields
	// ===========================================================

	private boolean in_title = false;
	private boolean in_link = false;
	private boolean in_item = false;

	private Localidad localidadDataSet = new Localidad();

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public Localidad getParsedData() {
		return this.localidadDataSet;
	}

	// ===========================================================
	// Methods
	// ===========================================================
	@Override 
     public void startDocument() throws SAXException { 
          this.localidadDataSet = new Localidad(); 
     }
	@Override
	public void endDocument() throws SAXException {
		// Nothing to do
	}

	/**
	 * Gets be called on opening tags like: <tag> Can provide attribute(s), when
	 * xml was like: <tag attribute="attributeValue">
	 */
	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		if (localName.equals("title")) {
			this.in_title = true;
		} else if (localName.equals("link")) {
			this.in_link = true;
		} else if (localName.equals("item")) {
			this.in_item = true;
		}
		
	      System.out.println("tElemento: " + localName);

	        for (int i = 0; i < atts.getLength(); i++) {
	         System.out.println("ttAtributo: " +
	          atts.getLocalName(i) + " = "+ atts.getValue(i));
	        }
	}

	/**
	 * Gets be called on closing tags like: </tag>
	 */
	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (localName.equals("title")) {
			this.in_title = false;
		} else if (localName.equals("link")) {
			this.in_link = false;
		} else if (localName.equals("item")) {
			this.in_item = false;
		}
	}

	/**
	 * Gets be called on the following structure: <tag>characters</tag>
	 */
	@Override
	public void characters(char ch[], int start, int length) {
		if (this.in_title)
			localidadDataSet.setTitle(new String(ch, start, length));
		if (this.in_link)
			localidadDataSet.setLink(new String(ch, start, length));
		
	}
}